package com.sine_x.wancai_android;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.gson.Gson;
import com.sine_x.wancai_android.model.CityEnum;
import com.sine_x.wancai_android.model.FunctionEnum;
import com.sine_x.wancai_android.model.IndustryEnum;
import com.sine_x.wancai_android.model.Company;
import com.sine_x.wancai_android.model.Favorite;
import com.sine_x.wancai_android.model.Jobs;
import com.sine_x.wancai_android.model.LoginAndRegister;
import com.sine_x.wancai_android.model.ProvinceEnum;
import com.sine_x.wancai_android.model.ResumeAbstract;
import com.sine_x.wancai_android.model.ResumeBasicInfo;
import com.sine_x.wancai_android.model.SimpleEnum;
import com.sine_x.wancai_android.model.SimpleResponse;
import com.sine_x.wancai_android.model.UserBasicInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 万才网接口
 */
public class Client {

    private static final Gson gson = new Gson();

    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL_LOGIN_REGISTER = "http://58.215.179.167/LoginAndRegiste.asmx";
    private static final String URL_BASIC_INFO = "http://58.215.179.167/BasicInfoManageInterface.asmx";
    private static final String URL_RESUME_MANAGER = "http://58.215.179.167/ResumeManageInterface.asmx";
    private static final String URL_JOB="http://58.215.179.167/JobManageInterface.asmx";

    private static final String OP_REGISTER = "UserRegister";
    private static final String OP_LOGIN = "MyLogin";
    private static final String OP_UPDATE_PASSWORD = "UpdatePassword";
    private static final String OP_GET_COMPANY_ENUM = "GetCompanyEnum";
    private static final String OP_GET_RESUME_ENUM = "GetResumeEnum";
    private static final String OP_GET_PROVINCE = "GetProvince";
    private static final String OP_GET_USER_BASIC_INFO_BY_USER_ID = "GetUserBasicInfoByUserId";
    private static final String OP_UPDATE_USER_BASIC_INFO = "UpdateUserBasicInfo";
    private static final String OP_GET_CITY_LIST = "GetCityList";
    private static final String OP_GET_RESUME_LIST = "GetResumeList";
    private static final String OP_CREATE_RESUME = "CreateResume";
    private static final String OP_GET_JOBS = "GetJobs";
    private static final String OP_GET_INDUSTRY = "GetIndustry";
    private static final String OP_GET_JOB_FUNCTION = "GetJobFunction";
    private static final String OP_GET_JOB_FUNCTION_BY_PARENT_ID = "GetJobFunctionByParentId";
    private static final String OP_GET_RESUME_BASIC_INFO_BY_ID = "GetResumeBasicInfoById";
    private static final String OP_DELETE_RESUME_BY_ID = "DeleteResumeById";
    private static final String OP_ADD_FAVORITE_JOB="AddFavoriteJob";
    private static final String OP_GET_COMINFO_BY_ID= "GetComInfoById";
    private static final String OP_GET_MY_JOB_FAVORITE_LIST="GetMyJobFavoriteList";
    private static final String OP_DELETE_MY_JOB_FAVORITE_BY_ID="DeleteMyJobFavoriteById";
    private static final String OP_GET_JOB_INFO_BY_ID="GetJobInfoById";

    /**
     * 调用接口
     * @param url 接口地址
     * @param op 方法名称
     * @param params 方法参数
     * @return 成功返回字符串，失败返回null
     */
    private static @Nullable String rpc(@NonNull String url, @NonNull String op, @NonNull Map<String, String> params) {
        SoapObject request = new SoapObject(NAMESPACE, op);
        for (Map.Entry<String, String> entry : params.entrySet())
            request.addProperty(entry.getKey(), entry.getValue());
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = request;
        envelope.dotNet = true;
        HttpTransportSE httpTransport = new HttpTransportSE(url);
        try {
            httpTransport.call(NAMESPACE + op, envelope);
            Object response = envelope.getResponse();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将JSON转换为Java Bean
     * @param json JSON字符串
     * @param objectClass 目标推向
     * @return 对象，失败返回null
     */
    private static @Nullable <T> T parseObject(@Nullable String json, @NonNull Class<T> objectClass) {
        if (json == null)
            return null;
        return gson.fromJson(json, objectClass);
    }

    public static String makeAllXsdDateTime(int year, int month, int dayOfMonth) {
        return String.format(Locale.CHINA, "%04d-%02d-%02d", year, month, dayOfMonth);
    }

    /**
     * 将类似{"total":12,"rows":[]}的JSON转换为对象数组
     * @param json 原始JSON字符串
     * @param itemClass 目标类型
     * @return 对象数组，失败返回null
     */
    private static @Nullable <T> ArrayList<T> parseArray(@Nullable String json, @NonNull Class<T> itemClass) {
        if (json == null)
            return null;
        try {
            ArrayList<T> items = new ArrayList<>();
            Gson gson = new Gson();
            JSONObject object = new JSONObject(json);
            JSONArray array = object.getJSONArray("rows");
            for (int i = 0; i < array.length(); i++) {
                String itemJson = array.getString(i);
                items.add(gson.fromJson(itemJson, itemClass));
            }
            return items;
        } catch (JSONException e) {
            return null;
        }
    }

    /* 登录和注册接口 */

    public static @Nullable LoginAndRegister userRegister(@NonNull String username, @NonNull String email, @NonNull String password) {
        Map<String, String> params = new HashMap<>();
        params.put("uName", username);
        params.put("pwd", password);
        params.put("email", email);
        String json = rpc(URL_LOGIN_REGISTER, OP_REGISTER, params);
        return parseObject(json, LoginAndRegister.class);
    }

    public static @Nullable LoginAndRegister myLogin(@NonNull String username, @NonNull String password) {
        Map<String, String> params = new HashMap<>();
        params.put("uName", username);
        params.put("pwd", password);
        String json = rpc(URL_LOGIN_REGISTER, OP_LOGIN, params);
        return parseObject(json, LoginAndRegister.class);
    }

    /* 基本信息接口 */

    public static @Nullable SimpleResponse updatePassword(@NonNull String username, @NonNull String oldPassword, @NonNull String newPassword) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", username);
        params.put("oldpwd", oldPassword);
        params.put("newpwd", newPassword);
        String json = rpc(URL_BASIC_INFO, OP_UPDATE_PASSWORD, params);
        return parseObject(json, SimpleResponse.class);
    }

    public static @Nullable ArrayList<IndustryEnum> getIndustry() {
        String json = rpc(URL_BASIC_INFO, OP_GET_INDUSTRY, new HashMap<String, String>());
        return parseArray(json, IndustryEnum.class);
    }

    public static @Nullable ArrayList<FunctionEnum> getJobFunction() {
        String json = rpc(URL_BASIC_INFO, OP_GET_JOB_FUNCTION, new HashMap<String, String>());
        return parseArray(json, FunctionEnum.class);
    }

    public static @Nullable ArrayList<FunctionEnum> getJobFunctionByParentId(String parentFuncId) {
        Map<String, String> params = new HashMap<>();
        params.put("parentFuncId", parentFuncId);
        String json = rpc(URL_BASIC_INFO, OP_GET_JOB_FUNCTION_BY_PARENT_ID, params);
        return parseArray(json, FunctionEnum.class);
    }

    public static @Nullable ArrayList<SimpleEnum> getCompanyEnum(int enumTypeID) {
        Map<String, String> params = new HashMap<>();
        params.put("enumTypeId", Integer.toString(enumTypeID));
        String json = rpc(URL_BASIC_INFO, OP_GET_COMPANY_ENUM, params);
        return parseArray(json, SimpleEnum.class);
    }

    public static @Nullable ArrayList<SimpleEnum> getResumeEnum(int enumTypeID) {
        Map<String, String> params = new HashMap<>();
        params.put("enumTypeId", Integer.toString(enumTypeID));
        String json = rpc(URL_BASIC_INFO, OP_GET_RESUME_ENUM, params);
        return parseArray(json, SimpleEnum.class);
    }

    public static @Nullable ArrayList<ProvinceEnum> getProvince() {
        String json = rpc(URL_BASIC_INFO, OP_GET_PROVINCE, new HashMap<String, String>());
        return parseArray(json, ProvinceEnum.class);
    }

    public static @Nullable ArrayList<CityEnum> getCityList(@NonNull String parentId) {
        Map<String, String> params = new HashMap<>();
        params.put("parentId", parentId);
        String json = rpc(URL_BASIC_INFO, OP_GET_CITY_LIST, params);
        Log.d("CityEnum", json);
        return parseArray(json, CityEnum.class);
    }

    public static @Nullable UserBasicInfo getUserBasicInfoByUserId(String userId) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        String json = rpc(URL_BASIC_INFO, OP_GET_USER_BASIC_INFO_BY_USER_ID, params);
        ArrayList<UserBasicInfo> infos = parseArray(json, UserBasicInfo.class);
        if (infos == null || infos.size() == 0)
            return null;
        return infos.get(0);
    }

    public static @Nullable SimpleResponse updateUserBasicInfo(String userId, String userName, int gender, String marriage, String birthday, String degree, String workyear, String mobile, String email, String location) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        params.put("userName", userName);
        params.put("gender", Integer.toString(gender));
        params.put("marriage", marriage);
        params.put("birthday", birthday);
        params.put("degree", degree);
        params.put("workyear", workyear);
        params.put("mobile", mobile);
        params.put("email", email);
        params.put("location", location);
        String json = rpc(URL_BASIC_INFO, OP_UPDATE_USER_BASIC_INFO, params);
        return parseObject(json, SimpleResponse.class);
    }

    /* 职位列表接口 */
    public static @Nullable ArrayList<Jobs> getJobs(int pageSize, int pageIndex) {
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", pageSize+"");
        params.put("pageIndex", pageIndex+"");
        params.put("industryId", "0");
        params.put("jobFunctionId", "0");
        params.put("workLocationId", "0");
        params.put("keywords", "");
        params.put("degreeId", "0");
        params.put("workexperienceId", "0");
        params.put("salaryRangeId", "0");
        params.put("jobNatureId", "0");
        String json = rpc(URL_JOB, OP_GET_JOBS, params);
        return parseArray(json, Jobs.class);
    }

    /* 获取职位接口 */
    public static @Nullable ArrayList<Jobs> getJobInfoById(String jobId) {
        Map<String, String> params = new HashMap<>();
        params.put("jobId", jobId+"");
        String json = rpc(URL_JOB, OP_GET_JOB_INFO_BY_ID, params);
        return parseArray(json, Jobs.class);
    }

    /* 收藏职位接口 */
    public static @Nullable SimpleResponse addFavoriteJob(String userId, String jobIds) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        params.put("jobIds", jobIds);
        String json = rpc(URL_JOB, OP_ADD_FAVORITE_JOB, params);
        return parseObject(json, SimpleResponse.class);
    }

    /* 获取公司信息接口 */
    public static @Nullable ArrayList<Company> getComInfoById(String companyId) {
        Map<String, String> params = new HashMap<>();
        params.put("companyId", companyId);
        String json = rpc(URL_JOB, OP_GET_COMINFO_BY_ID, params);
        return parseArray(json, Company.class);
    }

    /* 职位收藏列表接口 */
    public static @Nullable ArrayList<Favorite> getMyJobFavoriteList(String userId,int pageSize, int pageIndex) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        params.put("pagesize", String.valueOf(pageSize));
        params.put("pageindex", String.valueOf(pageIndex));
        params.put("keywords", "");
        String json = rpc(URL_JOB, OP_GET_MY_JOB_FAVORITE_LIST, params);
        Log.e("json",json);
        return parseArray(json, Favorite.class);
    }

    /* 删除收藏职位接口 */
    public static @Nullable SimpleResponse deleteMyJobFavoriteById(String id) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id);
        String json = rpc(URL_JOB, OP_DELETE_MY_JOB_FAVORITE_BY_ID, params);
        return parseObject(json, SimpleResponse.class);
    }




    /* 简历管理接口 */

    public static ArrayList<ResumeAbstract> getResumeList(String userId) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        String json = rpc(URL_RESUME_MANAGER, OP_GET_RESUME_LIST, params);
        return parseArray(json, ResumeAbstract.class);
    }

    public static SimpleResponse createResume(String userId, String resumeName, String userName,
                                              String gender, String marriage, String birthday, String degree,
                                              String workyear, String mobile, String email, String location,
                                              String policticalstatus, String seleveluation, String expectIndustryType,
                                              String expectJob, String expectLocation, int jobNature, String expectSalary) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        params.put("resumeName", resumeName);
        params.put("userName", userName);
        params.put("gender", gender);
        params.put("marriage", marriage);
        params.put("birthday", birthday);
        params.put("degree", degree);
        params.put("workyear", workyear);
        params.put("mobile", mobile);
        params.put("email", email);
        params.put("location", location);
        params.put("policticalstatus", policticalstatus);
        params.put("seleveluation", seleveluation);
        params.put("expectIndustryType", expectIndustryType);
        params.put("expectJob", expectJob);
        params.put("expectLocation", expectLocation);
        params.put("jobNature", String.valueOf(jobNature));
        params.put("expectSalary", expectSalary);
        String json = rpc(URL_RESUME_MANAGER, OP_CREATE_RESUME, params);
        return parseObject(json, SimpleResponse.class);
    }

    public static ResumeBasicInfo getResumeBasicInfoById(String resumeId) {
        Map<String, String> params = new HashMap<>();
        params.put("resumeId", resumeId);
        String json = rpc(URL_RESUME_MANAGER, OP_GET_RESUME_BASIC_INFO_BY_ID, params);
        Log.v("Resume", json);
        ArrayList<ResumeBasicInfo> arrayList = parseArray(json, ResumeBasicInfo.class);
        if (arrayList == null || arrayList.size() == 0)
            return null;
        return arrayList.get(0);
    }

    public static SimpleResponse deleteResumeById(@NonNull String resumeId) {
        Map<String, String> params = new HashMap<>();
        params.put("resumeId", resumeId);
        String json = rpc(URL_RESUME_MANAGER, OP_DELETE_RESUME_BY_ID, params);
        return parseObject(json, SimpleResponse.class);
    }
}
